package com.example.freemaker_demo.cli;

import cn.hutool.core.date.DateUtil;
import cn.hutool.log.StaticLog;
import com.example.freemaker_demo.entity.JavaTplEntity;
import com.example.freemaker_demo.entity.TemplateEntity;
import com.example.freemaker_demo.entity.VueTplEntity;
import com.example.freemaker_demo.executer.TemplateReplacer;
import com.example.freemaker_demo.executer.impl.JavaTemplateReplacerImpl;
import com.example.freemaker_demo.executer.impl.VueTemplateReplacerImpl;
import org.yaml.snakeyaml.Yaml;
import picocli.CommandLine;

import java.io.FileInputStream;
import java.util.Date;
import java.util.concurrent.Callable;

public class Template implements Callable<Integer> {
    @CommandLine.Option(names = {"-c", "--config"}, description = "Config file", required = true)
    String configFile;

    @CommandLine.Option(names = {"-o", "--output"}, description = "Output directory", required = true, defaultValue = "./output")
    String outputDir;

    @Override
    public Integer call() throws Exception {
        StaticLog.info("Start to replace template...");
        StaticLog.info("print some params:");
        StaticLog.info("configFile: {}", configFile);
        StaticLog.info("outputDir: {}", outputDir);

        FileInputStream yamlFile = new FileInputStream(configFile);
        TemplateEntity templateEntity = parseYaml(yamlFile);

        for (VueTplEntity vueTplEntity : templateEntity.getVue()) {
            if (!vueTplEntity.getEnable())
                continue;
            TemplateReplacer vueTemplateReplacer = new VueTemplateReplacerImpl()
                    .setVueTplEntity(vueTplEntity);

            vueTemplateReplacer.doReplace(resolveOutputDir(outputDir));
        }

        for (JavaTplEntity javaTplEntity : templateEntity.getJava()) {
            if (!javaTplEntity.getEnable())
                continue;
            TemplateReplacer javaTemplateReplacer = new JavaTemplateReplacerImpl()
                    .setJavaTplEntity(javaTplEntity);

            javaTemplateReplacer.doReplace(resolveOutputDir(outputDir));
        }
        return 0;
    }

    private TemplateEntity parseYaml(FileInputStream yamlFile) {
        Yaml yaml = new Yaml();
        return yaml.loadAs(yamlFile, TemplateEntity.class);
    }

    private String resolveOutputDir(String outputDir) {
        if (outputDir.charAt(outputDir.length() - 1) != '/') {
            outputDir += "/";
        }
        outputDir += (DateUtil.format(new Date(), "yyyy-MM-dd_HH-mm-ss") + "/");
        return outputDir;
    }
}
